import { prisma } from '../db/prisma';
import { createSuccessResponse, createErrorResponse } from '../utils/response';
import { z } from 'zod';
import { CompletionCycle } from '@prisma/client';

// 输入验证 schema
const createServiceSchema = z.object({
  serviceName: z.string().min(1).max(100),
  completionCycle: z.nativeEnum(CompletionCycle),
  cycleValue: z.number().int().positive().max(255).default(1),
  startDate: z.string().datetime().optional(),
  endDate: z.string().datetime().optional(),
  reminderFrequency: z.string().max(50).optional(),
  reminderContent: z.string().optional(),
});

const updateServiceSchema = z.object({
  id: z.number().int().positive(),
  serviceName: z.string().min(1).max(100).optional(),
  completionCycle: z.nativeEnum(CompletionCycle).optional(),
  cycleValue: z.number().int().positive().max(255).optional(),
  startDate: z.string().datetime().optional(),
  endDate: z.string().datetime().optional(),
  reminderFrequency: z.string().max(50).optional(),
  reminderContent: z.string().optional(),
});

const deleteServiceSchema = z.object({
  id: z.number().int().positive(),
});

const getServiceSchema = z.object({
  id: z.number().int().positive(),
});

const listServicesSchema = z.object({
  page: z.number().int().positive().default(1),
  pageSize: z.number().int().positive().max(100).default(10),
  search: z.string().optional(),
});

export class ServiceService {
  // 创建服务项目
  static async createService(input: z.infer<typeof createServiceSchema>) {
    try {
      const validatedInput = createServiceSchema.parse(input);
      
      // 检查服务名称是否已存在（包括已删除的）
      const existingService = await prisma.service.findFirst({
        where: { serviceName: validatedInput.serviceName }
      });
      
      if (existingService) {
        return createErrorResponse('服务项目名称已存在', 'SERVICE_NAME_EXISTS');
      }
      
      // 验证日期逻辑
      if (validatedInput.startDate && validatedInput.endDate) {
        const startDate = new Date(validatedInput.startDate);
        const endDate = new Date(validatedInput.endDate);
        
        if (startDate >= endDate) {
          return createErrorResponse('开始时间必须早于结束时间', 'INVALID_DATE_RANGE');
        }
      }
      
      // 创建服务项目
      const service = await prisma.service.create({
        data: {
          serviceName: validatedInput.serviceName,
          completionCycle: validatedInput.completionCycle,
          cycleValue: validatedInput.cycleValue,
          startDate: validatedInput.startDate ? new Date(validatedInput.startDate) : null,
          endDate: validatedInput.endDate ? new Date(validatedInput.endDate) : null,
          reminderFrequency: validatedInput.reminderFrequency,
          reminderContent: validatedInput.reminderContent,
        },
      });
      
      return createSuccessResponse(service, '服务项目创建成功');
    } catch (error) {
      console.error('创建服务项目失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('创建服务项目失败', 'CREATE_SERVICE_ERROR');
    }
  }
  
  // 更新服务项目
  static async updateService(input: z.infer<typeof updateServiceSchema>) {
    try {
      const validatedInput = updateServiceSchema.parse(input);
      
      // 检查服务项目是否存在
      const existingService = await prisma.service.findUnique({
        where: { 
          id: validatedInput.id
        }
      });
      
      if (!existingService) {
        return createErrorResponse('服务项目不存在', 'SERVICE_NOT_FOUND');
      }
      
      // 如果要更新服务名称，检查是否与其他服务冲突
      if (validatedInput.serviceName && validatedInput.serviceName !== existingService.serviceName) {
        const serviceNameExists = await prisma.service.findFirst({
          where: { 
            serviceName: validatedInput.serviceName,
            id: { not: validatedInput.id }
          }
        });
        
        if (serviceNameExists) {
          return createErrorResponse('服务项目名称已存在', 'SERVICE_NAME_EXISTS');
        }
      }
      
      // 验证日期逻辑
      const startDate = validatedInput.startDate ? new Date(validatedInput.startDate) : existingService.startDate;
      const endDate = validatedInput.endDate ? new Date(validatedInput.endDate) : existingService.endDate;
      
      if (startDate && endDate && startDate >= endDate) {
        return createErrorResponse('开始时间必须早于结束时间', 'INVALID_DATE_RANGE');
      }
      
      // 准备更新数据
      const updateData: any = {};
      if (validatedInput.serviceName !== undefined) updateData.serviceName = validatedInput.serviceName;
      if (validatedInput.completionCycle !== undefined) updateData.completionCycle = validatedInput.completionCycle;
      if (validatedInput.cycleValue !== undefined) updateData.cycleValue = validatedInput.cycleValue;
      if (validatedInput.startDate !== undefined) updateData.startDate = validatedInput.startDate ? new Date(validatedInput.startDate) : null;
      if (validatedInput.endDate !== undefined) updateData.endDate = validatedInput.endDate ? new Date(validatedInput.endDate) : null;
      if (validatedInput.reminderFrequency !== undefined) updateData.reminderFrequency = validatedInput.reminderFrequency;
      if (validatedInput.reminderContent !== undefined) updateData.reminderContent = validatedInput.reminderContent;
      
      // 更新服务项目
      const service = await prisma.service.update({
        where: { id: validatedInput.id },
        data: updateData,
      });
      
      return createSuccessResponse(service, '服务项目更新成功');
    } catch (error) {
      console.error('更新服务项目失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('更新服务项目失败', 'UPDATE_SERVICE_ERROR');
    }
  }
  
  // 硬删除服务项目
  static async deleteService(input: z.infer<typeof deleteServiceSchema>) {
    try {
      const validatedInput = deleteServiceSchema.parse(input);
      
      // 检查服务项目是否存在
      const existingService = await prisma.service.findUnique({
        where: { 
          id: validatedInput.id
        }
      });
      
      if (!existingService) {
        return createErrorResponse('服务项目不存在', 'SERVICE_NOT_FOUND');
      }
      
      // 硬删除服务项目（级联删除相关数据）
      await prisma.service.delete({
        where: { id: validatedInput.id }
      });
      
      return createSuccessResponse(null, '服务项目删除成功');
    } catch (error) {
      console.error('删除服务项目失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('删除服务项目失败', 'DELETE_SERVICE_ERROR');
    }
  }
  
  // 获取单个服务项目
  static async getService(input: z.infer<typeof getServiceSchema>) {
    try {
      const validatedInput = getServiceSchema.parse(input);
      
      const service = await prisma.service.findUnique({
        where: { 
          id: validatedInput.id
        },
        include: {
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          }
        }
      });
      
      if (!service) {
        return createErrorResponse('服务项目不存在', 'SERVICE_NOT_FOUND');
      }
      
      return createSuccessResponse(service, '获取服务项目成功');
    } catch (error) {
      console.error('获取服务项目失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取服务项目失败', 'GET_SERVICE_ERROR');
    }
  }
  
  // 获取服务项目列表
  static async listServices(input: z.infer<typeof listServicesSchema>) {
    try {
      const validatedInput = listServicesSchema.parse(input);
      const { page, pageSize, search } = validatedInput;
      
      // 构建查询条件
      const where: any = {};
      
      if (search) {
        where.OR = [
          { serviceName: { contains: search } },
          { reminderContent: { contains: search } },
        ];
      }
      
      // 获取总数
      const total = await prisma.service.count({ where });
      
      // 获取分页数据
      const services = await prisma.service.findMany({
        where,
        select: {
          id: true,
          serviceName: true,
          completionCycle: true,
          cycleValue: true,
          startDate: true,
          endDate: true,
          reminderFrequency: true,
          reminderContent: true,
          createdAt: true,
          updatedAt: true,
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          }
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      });
      
      const result = {
        data: services,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize),
        }
      };
      
      return createSuccessResponse(result, '获取服务项目列表成功');
    } catch (error) {
      console.error('获取服务项目列表失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取服务项目列表失败', 'LIST_SERVICES_ERROR');
    }
  }
}
